package com.chuji.crmcj.act;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.TryDriveInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.Jump;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.chuji.crmcj.view.CalendarView;
import com.chuji.crmcj.view.CalendarViewDialog;
import com.chuji.crmcj.view.NiceSpinner;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import com.chuji.crmcj.view.NiceSpinner;

public class DataCompleteActivity extends BaseActivity implements View.OnClickListener {
    //返回
    private ImageView iv_Back;
    //设为客流客户
    private LinearLayout ll_keliu;
    //客户基本信息
    private LinearLayout ll_client_basic_information;
    //购车相关信息
    private LinearLayout ll_try_drive_information;
    //客户类型信息
    private LinearLayout ll_client_type;
    //试乘试驾信息
    private LinearLayout ll_buy_car_information;
    private LinearLayout ll_try_drive_information1;
    /*试乘试驾信息存储*/
    List<TryDriveInfo.ApiParamObjEntity> tryDriveData;
    /*试乘试驾信息网络数据*/
    private TryDriveInfo tryDriveInfo;
    //    //数据
//    String[] forms = {"来电客户", "电销客户", "网销客户", "车展客户"};
//    //下拉框
    private NiceSpinner spinner;
    //适配器
    ArrayAdapter<String> adapter;
    //日期
    private LinearLayout ll_data;
    private TextView tv_data;
    //日历图片
    private ImageView iv_calendar;
    //管理器
    WindowManager windowManager;
    //日历显示Dialog
    CalendarViewDialog dialog;
    WindowManager.LayoutParams lp;
    //试驾申请
    private TextView tv_try_drive_apply;
    //客户状态
    private EditText et_client_state;
    String client_state;
    //提交数据
    private Button btn_submit;
    //客户类型
    private TextView tv_client_type;
    String clientType;
    //购买时机
    String buy_time;
    private String client_type;
    //
    private TextView mTv_client_follow;
    //意图
    private Intent mIntent;
    //请求码
    private int requestCode;
    //客户姓名
    String client_name;
    //客户号码
    String phoneNumber;
    //客户工作单位
    String work_place;
    //客户地址
    String address;
    //客户家庭
    String family_condition;
    //客户行业
    String trade;
    //客户爱好
    String interest;
    //购车用途
    String CarPurpose;
    //购买预算
    String CarBudget;
    //购买方式
    String CarMode;
    //车辆使用人
    String CarUser;
    //意向车系
    String CarSeries;
    //意向车型
    String CarModel;
    //意向配置
    String CarConfiguration;
    //意向颜色
    String CarColor;
    //竞品车型
    String CompetingModels;
    //关注原因
    String Reason;
    //客流ID
    String FlowID;
    //客户ID
    String CustomerID;
    //用户ID
    String SalesID;
    //传递过来的其他销售的ID
    String OriginalSalesID;
    //公司ID
    String CompanyID;

    @Override
    protected void onStart() {
        super.onStart();
        ll_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog = new CalendarViewDialog(DataCompleteActivity.this);
                dialog.show();
                dialog.calendar.setOnItemClickListener(new CalendarView.OnItemClickListener() {
                    @Override
                    public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
                        if (dialog.calendar.isSelectMore()) {

                        } else {
                            tv_data.setText(dialog.format.format(downDate));
                            dialog.dismiss();
                        }
                    }
                });
                windowManager = getWindowManager();
                lp = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
                //p.height = (int) (d.getHeight() * 0.3);   //高度设置为屏幕的0.3
                lp.width = windowManager.getDefaultDisplay().getWidth();//为获取屏幕宽、高,宽度设置为全屏
                dialog.getWindow().setAttributes(lp);     //设置生效
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_data_complete);
        //得到控件
//        spinner = (NiceSpinner) findViewById(R.id.sp_data);
        tv_client_type = (TextView) findViewById(R.id.tv_client_type);
        tv_data = (TextView) findViewById(R.id.tv_data);
        ll_data = (LinearLayout) findViewById(R.id.ll_data);
//        mTv_client_follow = (TextView) findViewById(R.id.tv_client_follow);
        tv_try_drive_apply = (TextView) findViewById(R.id.tv_try_drive_apply);
        iv_calendar = (ImageView) findViewById(R.id.iv_calendar);
        iv_Back = (ImageView) findViewById(R.id.iv_Back);
        ll_keliu = (LinearLayout) findViewById(R.id.ll_keliu);
        ll_client_basic_information = (LinearLayout) findViewById(R.id.ll_client_basic_information);
        ll_buy_car_information = (LinearLayout) findViewById(R.id.ll_buy_car_information);
        ll_client_type = (LinearLayout) findViewById(R.id.ll_client_type);
        ll_try_drive_information = (LinearLayout) findViewById(R.id.ll_try_drive_information);
        ll_try_drive_information1 = (LinearLayout) findViewById(R.id.ll_try_drive_information1);
        et_client_state = (EditText) findViewById(R.id.et_client_state);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        //得到传递过来的值
        Intent intent = getIntent();
        OriginalSalesID = intent.getStringExtra("OriginalSalesID");
        FlowID = intent.getStringExtra("FlowID");
        SalesID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        if (OriginalSalesID != null) {
            ll_keliu.setVisibility(View.INVISIBLE);
        }
        //请求数据
        initDa();
        //设置为客流客户
        ll_keliu.setOnClickListener(this);
        //跳转到客户基本信息界面
        ll_client_basic_information.setOnClickListener(this);
        //跳转到购车相关信息界面
        ll_buy_car_information.setOnClickListener(this);
        //跳转到试乘试驾信息界面
        ll_try_drive_information1.setOnClickListener(this);
        //跳转到选择客户类型界面
        ll_client_type.setOnClickListener(this);
        //返回
        iv_Back.setOnClickListener(this);
        //试驾申请
        tv_try_drive_apply.setOnClickListener(this);
        //提交数据
        btn_submit.setOnClickListener(this);
        //根据数据改变客户类型

        //创建adapter对象
//        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, forms);
//        //填充
//        spinner.setAdapter(adapter);
//        //spinner.setSelected(false);
//        //添加itemSeleted事件
//        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                              /**
//                                               * 当元素被选中的时候自动调用
//                                               * 参数1：parent-->spinner
//                                               * 参数2：view-->当前子项元素的布局 TextView
//                                               * 参数3： postion-->当前选中元素的索引
//                                               * 参数4：当前选中的子项元素的控件在ListView中索引位置
//                                               */
//                                              @Override
//                                              public void onItemSelected(AdapterView<?> parent, View view,
//                                                                         int position, long id) {
//                                                  //获取选取的用户类型
//                                                  client_type=forms[position];
//                                                  UIUtils.showToastSafe("选中了"+client_type+"类型");
//                                              }
//
//                                              /**
//                                               * 没有选中。。自动调用
//                                               */
//                                              @Override
//                                              public void onNothingSelected(AdapterView<?> parent) {
//                                                  // TODO Auto-generated method stub
//                                              }
//                                          }
//
//        );
    }

    @Override
    protected void initData() {

    }

    private void initDa() {
        /**
         * 获得试驾信息
         */
        getTryDriveData();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    private void getTryDriveData() {
        //第一次
        if (tryDriveData == null) {
            tryDriveData = new ArrayList<TryDriveInfo.ApiParamObjEntity>();
        }
        requestStandData();
    }

    private void requestStandData() {
        //初始化Volley
        Intent intent = getIntent();
        CustomerID = intent.getStringExtra("CustomerID");
        String strURL = String.format(UrlUtils.TRY_DRIVE_SHOW + "&CustomerID=" + CustomerID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                tryDriveInfo = JSON.parseObject(response, TryDriveInfo.class);
                tryDriveData.addAll(tryDriveInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (tryDriveInfo.getCount() == 0) {
                            ll_try_drive_information.setVisibility(View.GONE);
                        } else {
                            ll_try_drive_information.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //客户类型返回数据
        clientType = data.getStringExtra("clientType");
        // 根据上面发送过去的请求码来区别
        switch (requestCode) {
            case 0:
                if (clientType.equals(" ")) {
                    tv_client_type.setText(" ");
                } else {
                    tv_client_type.setText(clientType);
                }
                break;
            case 10:
                //客户信息返回数据
                client_name = data.getStringExtra("Name");
                phoneNumber = data.getStringExtra("Tel");
                work_place = data.getStringExtra("WorkPlace");
                address = data.getStringExtra("HomeAddress");
                family_condition = data.getStringExtra("HomeInfo");
                trade = data.getStringExtra("Profession");
                interest = data.getStringExtra("Hobbies");
                break;
            case 11:
                //客户信息返回数据
                CarPurpose = data.getStringExtra("CarPurpose");
                CarBudget = data.getStringExtra("CarBudget");
                CarMode = data.getStringExtra("CarMode");
                CarUser = data.getStringExtra("CarUser");
                CarSeries = data.getStringExtra("CarSeries");
                CarModel = data.getStringExtra("CarModel");
                CarConfiguration = data.getStringExtra("CarConfiguration");
                CarConfiguration = data.getStringExtra("CarConfiguration");
                CarColor = data.getStringExtra("CarColor");
                CompetingModels = data.getStringExtra("CompetingModels");
                Reason = data.getStringExtra("Reason");
                break;
            default:
                break;
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_client_basic_information:
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), ClientInforActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 10;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_buy_car_information:
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), BuyCarInforActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 11;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_try_drive_information1:
                Jump.toNextActivity(DataCompleteActivity.this, TryDriveDetailActivity.class);
                break;
            case R.id.ll_client_type:
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), ClientTypeChooseActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 0;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.iv_Back:
                finish();
                break;
            case R.id.ll_keliu:
                /**
                 *  弹出消息框
                 */
                showNoWorthDialog();
//                new AlertDialog.Builder(DataCompleteActivity.this)
//                        .setMessage("设为客流客户?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        //进行移除客户操作
//                        new Thread() {
//                            public void run() {
//                                UIUtils.showToastSafe("设为客流客户成功");
//                            }
//                        }.start();
//                    }
//                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).show();
                break;
            case R.id.tv_try_drive_apply:
                /**
                 *  弹出消息框
                 */
                showDriveApplyDialog();
                break;
            case R.id.btn_submit:
                //获取销售员输入的信息
                client_state = et_client_state.getText().toString();
                //获取用户选择的购买时间
                buy_time = tv_data.toString();
                CompanyID = SPUtils.getString(UIUtils.getContext(), "CompanyID", "");
                if (TextUtils.isEmpty(client_state) || CommonUtil.isEmpty(client_name) || CommonUtil.isEmpty(CarPurpose)) {
                    UIUtils.showToastSafe("必填项还没有填写");
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("SalesID", SalesID);
                    map.put("FlowID", FlowID);
                    map.put("CompanyID", CompanyID);
                    map.put("Name", client_name);
                    map.put("Tel", phoneNumber);
                    map.put("WorkPlace", work_place);
                    map.put("HomeAddress", address);
                    map.put("HomeInfo", family_condition);
                    map.put("Profession", trade);
                    map.put("Hobbies", interest);
                    map.put("CustomerType", client_state);
                    map.put("PredictBuyTime", buy_time);
                    map.put("Comment", clientType);
                    map.put("CarPurpose", CarPurpose);
                    map.put("CarBudget", CarBudget);
                    map.put("CarMode", CarMode);
                    map.put("CarUser", CarUser);
                    map.put("CarSeries", CarSeries);
                    map.put("CarModel", CarModel);
                    map.put("CarConfiguration", CarConfiguration);
                    map.put("CarColor", CarColor);
                    map.put("CompetingModels ", CompetingModels);
                    map.put("Reason", Reason);
                    postRequest(UrlUtils.COMMIT_CLIENT_INFO, map, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            UIUtils.showToastSafe("提交成功");
                        }
                    });
//                    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
//                    StringRequest stringRequest = new StringRequest(Request.Method.POST, UrlUtils.COMMIT_CLIENT_INFO,
//                            new Response.Listener<String>() {
//                                @Override
//                                public void onResponse(String response) {
//                                    UIUtils.showToastSafe("提交成功");
//                                }
//                            }, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//                            UIUtils.showToastSafe("提交失败，请检查网络");
//                        }
//                    }) {
//                        @Override
//                        protected Map<String, String> getParams() {
//                            //在这里设置需要post的参数
//                            Map<String, String> map = new HashMap<String, String>();
//                            map.put("SalesID",SalesID);
//                            map.put("FlowID",FlowID);
//                            map.put("CompanyID",CompanyID);
//                            map.put("Name",client_name);
//                            map.put("Tel",phoneNumber);
//                            map.put("WorkPlace",work_place);
//                            map.put("HomeAddress",address);
//                            map.put("HomeInfo",family_condition);
//                            map.put("Profession",trade);
//                            map.put("Hobbies",interest);
//                            map.put("CustomerType",client_state);
//                            map.put("PredictBuyTime",buy_time);
//                            map.put("Comment",clientType);
//                            map.put("CarPurpose",CarPurpose);
//                            map.put("CarBudget",CarBudget);
//                            map.put("CarMode",CarMode);
//                            map.put("CarUser",CarUser);
//                            map.put("CarSeries",CarSeries);
//                            map.put("CarModel",CarModel);
//                            map.put("CarConfiguration",CarConfiguration);
//                            map.put("CarColor",CarColor);
//                            map.put("CompetingModels ",CompetingModels);
//                            map.put("Reason",Reason);
//                            return map;
//                        }
//                    };
//                    requestQueue.add(stringRequest);
                }
                break;
            default:
                break;
        }
    }

    private void showNoWorthDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_no_worth_client, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FlowID = "";
                String strURL = String.format(UrlUtils.SET_TO_RUN_OF_CLIENT + "&FlowID =" + FlowID);
                StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        UIUtils.showToastSafe("已设置为客流客户");
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        System.out.println("失败" + error);
                        UIUtils.showToastSafe("请检查网络");
                    }
                });
                // Add the request to the RequestQueue.
                VolleyUtil.getRequestQueue().add(stringRequest);
                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void showDriveApplyDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_try_drive_apply, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                CustomerID = intent.getStringExtra("CustomerID");
                String strURL = String.format(UrlUtils.APPLY_TRY_DRIVE + "&FlowID =" + FlowID + "&SalesID =" + SalesID + "&CustomerID =" + CustomerID);
                StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        UIUtils.showToastSafe("申请试驾成功");
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        System.out.println("失败" + error);
                        UIUtils.showToastSafe("请检查网络");
                    }
                });
                // Add the request to the RequestQueue.
                VolleyUtil.getRequestQueue().add(stringRequest);
                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
